<?php include 'header.php'; ?>
<script type="text/javascript">
//<![CDATA[
var map;
var req;
var day_add = '<?=$_GET['day_add']==null?'0':$_GET['day_add']?>';
var latitude = <?=$_GET['latitude']==null?'37.552224':$_GET['latitude']?>;
var longitude = <?=$_GET['longitude']==null?'126.923311':$_GET['longitude']?>;
//var tried = false;

initHotspot();
function initHotspot() {
	var url = "http://gilstar.com/gilstar/Performance.jsp";
	var obj = new Object();
	obj.req = "GET_HOTSPOT_LIST";
	req = obj.req;
	
	getJSON(url, obj);
}

function initMap()
{
	var position = new Object();
	showDefaultMap();

	if (<?=($_GET['latitude']!=null && $_GET['longitude'] !=null)?'true':'false'?>) {
		return;
	}
	
	if(Modernizr.geolocation)	//geolocation support check
	{
		navigator.geolocation.getCurrentPosition(showMap, handleError, {enableHighAccuracy : true, maximumAge : 75000});
	}
	else
	{
		alert("위치정보 서비스가 지원되지 않습니다.");
	}
}

function hotSpot(spot)
{
	if (spot == 'my')
	{
		initMap();	
	}
	else
	{
		var position = new Object();
		position.coords = new Object();
		latitude = spot.split(',')[0];
		longitude = spot.split(',')[1];
		showDefaultMap();
	}
}
function refresh(day) {
	day_add = day;
	showDefaultMap();
}

function showDefaultMap() {
	var position = new Object();
	position.coords = new Object();
	position.coords.latitude = latitude;
	position.coords.longitude = longitude;
	showMap(position);
}

function showMap(position)
{
	latitude = position.coords.latitude;
	longitude = position.coords.longitude;
	
	var currentLocation = new google.maps.LatLng(latitude, longitude);
	var myOptions = { zoom: 16, center: currentLocation, mapTypeId: google.maps.MapTypeId.ROADMAP };
	map = new google.maps.Map(document.getElementById("map_api"), myOptions);			
	var marker = new google.maps.Marker(
			{
				icon : "http://i1.daumcdn.net/imgsrc.search/local_coll/ico_here_new.png",
				position : currentLocation,
				title : "내 위치",
				map : map
			});

	//add eventlisteners(드래그 끝나는 시점에서 다시 공연리스트 가져옴) TODO 마커 리셋
	google.maps.event.addListener(map, 'dragstart', function() 
		{
			getPerformanceListForMap();
		});
	
	getPerformanceListForMap();
}

function handleError(err)
{
	var code = err.code;
	//code의 종류에 1번은 사용자가 위치정보를 공유안함, 2번은 네트워크에 문제 발생, 3번은 시간이 너무 오래 걸림
	//4번은 알 수 없는 오류 발생.
	var message = err.message;		//최종 사용자를 위한 용도가 아님. 
	
}

function getJSON(url, json)
{
	var requestStr = JSON.stringify(json, replacer);
	console.log(requestStr);
	
	$.ajax(
		{
			url: url,
			data: requestStr,
			type: "POST",
			success: function(data)
			{
				var resultObject = jQuery.parseJSON(data);
				jsonResponseHandler(resultObject);
			},
			fail: function(data)
			{
				alert(data);
			}
		});
}

function jsonResponseHandler(result)
{
	if(result.ResultCode == -1)			//처리 도중 실패.
	{
		alert(result.ResultMessage);
	}
	else if(result.ResultCode == 0)	//성공적으로 처리 완료.
	{
		if (req == 'GET_PERFORMANCE_FROM_MAP') {
			document.getElementById('mapCount').innerHTML = result.ResultMethod.length;
			noticeDisplay('');
			
			for(var nIndex = 0; nIndex < result.ResultMethod.length; nIndex++)
			{
				var items = result.ResultMethod[nIndex];	//access by array index.
				var latlng = new google.maps.LatLng(items.latitude, items.longitude);
				var icon = 'img/marker_'+items.category+'.png';
				try {
					if (items.time.split(' ')[1].split(':')[0] >= new Date().getHours()) {
						icon = 'img/marker_'+items.category+'_on.png';
					}
				} catch(e){}
				var marker = new google.maps.Marker(
						{
							icon : icon,
							position : latlng,
							title : items.title + ", 시간 : " + items.time,
							map : map
						});
				
				markerListener(marker, items);
			}
		} else if (req == 'GET_HOTSPOT_LIST') {
			var selectBox = document.getElementById('setLocation');
			selectBox.length = 0;
			selectBox.options[0] = new Option('내 주변', 'my');
			for(var nIndex = 0; nIndex < result.ResultMethod.length; nIndex++) {
				spot = result.ResultMethod[nIndex];	//access by array index.
				selectBox.options[nIndex+1] = new Option(spot.name, (spot.latitude + ',' + spot.longitude));
			}
			initMap();
		}
	}
}

function markerListener(marker, items)
{
	google.maps.event.addListener(marker, 'click', function() 
			{
				showPinLayer(items.performance_seq, items.title, items.artist, items.category, items.address, items.time);
			}
	);
}

function showPinLayer(seq, title, artist, category, address, time)
{
	var html = '<h3 class="pinLayerH"><a href="#" onclick="view('+seq+')" >' + title +  '</a><span class="pinLayerDiv">|</span>';
	html += artist + '&nbsp; <a href="#" onclick="pinDisplay(\'none\');return false;">x</a></h3>';
	html += '<ul class="pinLayerUl">';
	html += '<li class="pinLayerLi">' + categories[category] + '</li>';
	html += '<li class="pinLayerLi">' + address + '</li>';
	times = time.split(' ')[1].split(':');
	html += '<li class="pinLayerLi"><time datetime="' + time + '">' + times[0]+':'+times[1] + ' ~</time></li>';
	html += '</ul>';
	document.getElementById('pinLayer').innerHTML = html;
	pinDisplay('');
}
function pinDisplay(display)
{
	document.getElementById('pinLayer').style.display = display;
}
function noticeDisplay(display)
{
	document.getElementById('noticeLayer').style.display = display;
}

function getPerformanceListForMap()
{
	var url = "http://gilstar.com/gilstar/Performance.jsp";
	var obj = new Object();
	obj.req = "GET_PERFORMANCE_FROM_MAP";
	req = obj.req;
	obj.day_add = day_add;
	document.getElementById('listDate_'+day_add).className = 'listDateLi listDateLiSelected';
	document.getElementById('listDate_'+(1-day_add)).className = 'listDateLi';
	pinDisplay('none');
		
	var bounds = map.getBounds();
	if (bounds == null) {
//		if (!tried) {
//			showDefaultMap();
//		}
//		tried = true;
		return;
	}
	/*
	var north_east = new Object();
	north_east.latitude = bounds.getNorthEast().lat();
	north_east.longitude = bounds.getNorthEast().lng();
	
	var south_west = new Object();
	south_west.latitude = bounds.getSouthWest().lat();
	south_west.longitude = bounds.getSouthWest().lng();
	
	obj.north_east = north_east;
	obj.south_west = south_west;
	*/
	
	var pos = map.getCenter();
	obj.latitude = pos.lat();
	obj.longitude = pos.lng();
	
	getJSON(url, obj);
}

function view(seq) {
	location.href= 'view.php?performance_seq=' + seq + '&latitude=' + latitude + '&longitude' + longitude;
}

function replacer(key, value) 
{
    if (typeof value === 'number' && !isFinite(value)) 
    {
        return String(value);
    }
    return value;
}

function encodeURL(str){
    var s0, i, s, u;
    s0 = "";                // encoded str
    for (i = 0; i < str.length; i++)
    {
        s = str.charAt(i);
        u = str.charCodeAt(i);          // get unicode of the char
        if (s == " ")
        {
        	s0 += "20";	// SP should be converted to "+"
        }
        else 
        {
            if ((u >= 0x0) && (u <= 0x7f))    // single byte format
            {
                s = "0"+u.toString(16);
                s0 += s.substr(s.length-2);
            }
            else if (u > 0x1fffff)	// quaternary byte format (extended)
            {    
                s0 += (oxf0 + ((u & 0x1c0000) >> 18)).toString(16);
                s0 += (0x80 + ((u & 0x3f000) >> 12)).toString(16);
                s0 += (0x80 + ((u & 0xfc0) >> 6)).toString(16);
                s0 += (0x80 + (u & 0x3f)).toString(16);
            }
            else if (u > 0x7ff)	// triple byte format
            {        
                s0 += (0xe0 + ((u & 0xf000) >> 12)).toString(16);
                s0 += (0x80 + ((u & 0xfc0) >> 6)).toString(16);
                s0 += (0x80 + (u & 0x3f)).toString(16);
            }
            else 			// double byte format
            {                      
                s0 += (0xc0 + ((u & 0x7c0) >> 6)).toString(16);
                s0 += (0x80 + (u & 0x3f)).toString(16);
            }
        }
    }

    return s0;
}

//]]>
</script>

<!-- 지도 보기 -->
<section id="map">
	<h1 class="hidden">지도 보기</h1>
	<!-- 지도 -->
	<h2 class="hidden">지도</h2>
	<div class="map">

		<div class="map_api" id="map_api" style="height: 300px;">
			<img src="img/@map.png" alt="@지도">
		</div>

		<!-- [D] style 속성의 left(x), top(y) 속성을 이용해 핀의 위치를 조정하세요. -->
		<!-- button type="button" class="pin pinMe" style="left:140px;top:160px">내 위치: 홍대 걷고 싶은 거리</button>
		<button type="button" class="pin" style="left:220px;top:120px">홍대 놀이터 옆 골목</button-->
		<div class="pinLayer" id="pinLayer" style="left:100px;top:45px;display:none;">
		</div>
		<div class="map_notice_wrap" id="noticeLayer">
			<div class="map_notice">
				<p>주변에 총 <strong class="map_notice_s" id="mapCount">0</strong>개의 공연이 있습니다.</p>
				<button type="button" class="map_notice_close" onclick="noticeDisplay('none')">닫기</button>
			</div>
		</div>

	</div>
	<div class="viewOption">
		<ul class="listDate">
		<li id="listDate_0" class="listDateLi listDateLiSelected"><a href="#" class="listDateA" onclick="refresh('0');return false;">오늘</a></li>
		<li id="listDate_1" class="listDateLi"><a href="#" class="listDateA" onclick="refresh('1');return false;">내일</a></li>
		</ul>
		<label for="setLocation" class="hidden">위치설정</label>
		<select id="setLocation" class="setLocation" onchange="hotSpot(this.value);">
		<option selected>내 주변</option>
		<option>홍대</option>
		<option>대학로</option>
		<option>강남</option>
		<option>대구</option>
		<option>부산</option>
		</select>
	</div>

	<!-- //지도 -->
</section>
<!-- //지도 보기 -->

<?php //include 'footer.php'; ?>
